package com.leyou.controller;

import com.leyou.common.vo.PageResult;
import com.leyou.dto.SkuDTO;
import com.leyou.dto.SpuDTO;
import com.leyou.dto.SpuDetailDTO;
import com.leyou.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    /**
     * 分页查询spu
     *
     * @param page     当前页
     * @param rows     每页大小
     * @param saleable 上架商品或下降商品
     * @param key      关键字
     * @return 当前页商品数据
     */
    @GetMapping("spu/page")
    public ResponseEntity<PageResult<SpuDTO>> querySpuByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "saleable", required = false) Boolean saleable,
            @RequestParam(value = "key", required = false) String key
    ) {
        return ResponseEntity.ok(goodsService.querySpuByPage(page, rows, saleable, key));
    }

    /*
     * 新增商品
     * */
    @PostMapping
    public ResponseEntity<Void> saveGoods(@RequestBody SpuDTO spuDTO) {
        this.goodsService.save(spuDTO);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    /**
     * 修改商品上下架
     *
     * @param id       商品的spu的id
     * @param saleable true:上架; false:下架
     */
    @PutMapping("spu/saleable")
    public ResponseEntity<Void> updateSpuSaleable(@RequestParam("id") Long id, @RequestParam("saleable") Boolean saleable) {
        goodsService.updateSaleable(id, saleable);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 根据id查询spu
     *
     * @param spuId
     * @return spu对象，包含spuDetail和skus
     */
    @GetMapping("/spu/{id}")
    public ResponseEntity<SpuDTO> querySpuById(@PathVariable("id") Long spuId) {

        return ResponseEntity.ok(goodsService.querySpuById(spuId));

    }

    /**
     * 修改商品
     *
     * @param spu
     */
    @PutMapping("goods")
    public ResponseEntity<Void> updateGoods(@RequestBody SpuDTO spu) {
        goodsService.updateGoods(spu);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();


    }
    /*
    * 根据spu查询sku
    * */
    @GetMapping("/sku/of/spu")
    public  ResponseEntity<List<SkuDTO>> querySkuBySpuId(@RequestParam("id") Long id){
        return ResponseEntity.ok(goodsService.querySkuBySpuId(id));
    }

    /*
    * 根据spuId,查询spuDetail
    * */
    @GetMapping("/spu/detail")
    public ResponseEntity<SpuDetailDTO> queryDetailById(@RequestParam("id") Long id){
        return ResponseEntity.ok(goodsService.querySpuDetailBySpuId(id));
    }


}
